package dao;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import common.HibernateUtil;
import common.Pager;
import model.Course;

public class CourseDAO {
	public void update(Course course) {
		Session session=HibernateUtil.openSession();
		session.beginTransaction();
		session.saveOrUpdate(course);
		session.getTransaction().commit();
		session.close();
	}
	
	//显示数据的多少
	@SuppressWarnings("unchecked")
	public List<Course> getCourses(Pager pager){
		String hql="from Course";
		Session session=HibernateUtil.openSession();
		Query query=session.createQuery(hql);
		session.beginTransaction();
		//返回当前页的记录
		//1.设置当前页从第几条记录开始显示
		query.setFirstResult((pager.getPageNo()-1)*pager.getPageSize());
		//2.最多显示多少条数据
		query.setMaxResults(pager.getPageSize());
		List<Course> list=query.list();
		
		session.getTransaction().commit();
		session.close();
		return list;		
	}
	
	//获得总页数
	@SuppressWarnings("unchecked")
	public void initPage(Pager pager) {
		String hql="from Course";
		Session session=HibernateUtil.openSession();
		Query query=session.createQuery(hql);
		session.beginTransaction();
		List<Course> list=query.list();//此处得到了教室的总个数
		pager.setPageCount(list.size()/pager.getPageSize());//计算总页数
		
		if(list.size()%pager.getPageSize()>0) {
			pager.setPageCount(pager.getPageCount()+1);
		}

		session.getTransaction().commit();
		session.close();
	}
	//删除课程
	public void delete(Course course) {
		Session session=HibernateUtil.openSession();
		session.beginTransaction();
		session.delete(course);
		session.getTransaction().commit();
		session.close();		
	}
	
	//修改课程
	public Course get(Course course) {
		Session session=HibernateUtil.openSession();
		session.beginTransaction();
		String hql="from Course where id=:id";
		Query query=session.createQuery(hql)
				.setProperties(course);//通过id得到教室的信息
		Course r=(Course) query.uniqueResult();
		session.getTransaction().commit();
		session.close();
		return r;
	}
}
